package com.example.demo.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.demo.constant.CommonConstant;
import com.example.demo.domains.SysUser;
import com.example.demo.enums.ResultStatue;
import com.example.demo.service.SysUserService;
import com.example.demo.utils.CommonUtil;
import com.example.demo.utils.IpUtil;
import com.example.demo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 处理登录业务
 * User: lyh
 * Date: 2017/8/2
 * Time: 15:56
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private JedisPool jedisPool;


    /**
     * 获取所有的用户信息
     * */
    @GetMapping("/getuser")
    public Object getUser(){
        Map<String,List<SysUser>> resultMap = new HashMap<>();
        resultMap.put("users",sysUserService.getAll());
        return resultMap;
    }
    /**
     * 登录处理
     * @param username 用户名
     * @param password 密码
     * */
    @PostMapping("/dologin")
    public Object doLogin(@RequestParam(name="username",required = true)String username,
                          @RequestParam(name="password",required = true)String password,
                          HttpServletRequest request){
        LOGGER.info("dologin request--> username:{},password:{}",username,password);
        Jedis jedis = jedisPool.getResource();
        SysUser sysUser = sysUserService.getOneSysUserByUserName(username);
        if(sysUser==null){
            return ResultUtil.error(ResultStatue.LOGIN_USER_NULL);
        }
        if(!password.equals(sysUser.getPassword())){
            return ResultUtil.error(ResultStatue.LOGIN_ERROR);
        }
        if(jedis.get(CommonConstant.CACHE_USER+sysUser.getId())!=null){
            /**存在有效登录*/
            jedis.del(CommonConstant.CACHE_USER+sysUser.getId());
        }
        //获取ip地址
        String ip = IpUtil.getRemoteHost(request);
        String seesionId = CommonUtil.randomUUID();
        //生成令牌
        /**验证成功，则保存用户信息到redis中*/
        jedis.setex(seesionId,30, JSONObject.toJSONString(sysUser));
        Map<String,String> data = new HashMap<>();
        data.put("sessionId",seesionId);
        return ResultUtil.success(data);
    }

    /**
     * 注册处理
     *
     * */
    @PostMapping("/doregister")
    public Object doRegister(@RequestParam(name="username",required = true)String username,
                            @RequestParam(name="password",required = true)String password,
                             @RequestParam(name="repassword",required = true)String repassword,
                            @RequestParam(name="email",required = true)String email){
        LOGGER.info("doRegister request--> username:{},password:{},repassword:{},email:{}",username,password,repassword,email);
        if(checkUsernameIsExisInDb(username)){
            return ResultUtil.error(ResultStatue.REGISTER_USER_INUSE);
        }
        SysUser sysUser = new SysUser();
        sysUser.setEmail(email);
        sysUser.setUsername(username);
        sysUser.setPassword(password);
        sysUser.setSalt("proframe");
        sysUser.setStatus(0);
        sysUserService.saveUser(sysUser);
        return ResultUtil.success();
    }

    private boolean checkUsernameIsExisInDb(String username) {
        SysUser sysUser = sysUserService.getOneSysUserByUserName(username);
        if(sysUser!=null){
            return true;
        }
        return false;
    }


}
